import { Component, NgZone, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';
import { AutopartsService } from '@core/services/autoparts/autoparts.service';
import { Subscription } from 'rxjs';
import { ApesMessageService } from '@shared/apes/message';
import { UserInfo } from 'os';
import { UserAuthService } from '@core/services/user-auth.service';
import { AutopartsViewService } from '@core/services/autoparts/autoparts.view.service';

@Component({
  selector: 'epc-parts-list',
  templateUrl: './epc-parts-list.component.html',
  styleUrls: ['./epc-parts-list.component.scss'],
  encapsulation: ViewEncapsulation.None,
})

export class EpcPartsListComponent implements OnInit, OnDestroy {

  private subscription: Subscription;

  domain = 'http://10.2.16/';

  isAllDisplayDataChecked = false; // 全选
  isIndeterminate = false; // 不确定
  numberOfChecked = 0; // 选中数量
  mapOfCheckedId: { [key: string]: boolean } = {}; // 缓存选中的

  checkCacheList = [];

  listOfData = [];

  constructor(
    private msg: ApesMessageService,
    private userAuthService: UserAuthService,
    private autopartsViewService: AutopartsViewService,
    private autopartsService: AutopartsService) {

  }

  ngOnInit(): void {
    this.subscription = this.autopartsViewService.partsListChange$.subscribe((data: any) => {
      this.mapOfCheckedId = {};
      if (data && data.data) {
        data.data.forEach(item => {
          item.previewVisible = false;
          if (item.imgName) {
            item.imageName = item.imgName.split(';').map(url => `${this.domain}/${url}`);
          } else {
            item.imageName = [];
          }
        });
        this.listOfData = data.data;
        console.log('查询出来的配件为：', data);
      } else {
        this.listOfData = [];
      }
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  /***
   * 新增代办
   */
  handleClick() {
    let requestJson = this.requestCore({}, true);
    if(requestJson.partChineseName && requestJson.partChineseName.length === 0) {
      this.msg.error("当前选中全为非编译数据");
      return;
    };
    this.autopartsService.addToDo(requestJson).subscribe(data => {
      if (data && data.message) {
        // 清空选中项
        this.mapOfCheckedId = {};
      }
    })
  }

  /***
   * 确认编译(0:否 1: 是)
   */
  handleConfirmClick(parseSign: number) {
    this.autopartsService.updateParseSign(this.requestCore({ parseSign }, false)).subscribe((data) => {
      if (data && data.message) {
        // 根据parseSign标记更新数据
        this.listOfData.filter(item => this.mapOfCheckedId[item.partChineseName])
          .forEach((item) => {
            if (parseSign === 0) {
              item.parseSign = 0;
              item.partDescName = '';
            } else {
              item.parseSign = 1;
            }
          });
        this.mapOfCheckedId = {}; // 清空选中项
      }
    });
  }

  // 拼接请求参数
  private requestCore(param, parseSign) {
    const userInfo = this.userAuthService.getUserInfoObj();
    let userId = null;
    let userName = null;
    if (userInfo && userInfo.userAccount) {
      userId = userInfo.userAccount.id;
      userName = userInfo.userAccount.name;
    }

    let requestJson = {
      userId: userId,
      userName: userName,
      menuId: this.listOfData[0].menuId,
      menuName: this.listOfData[0].menuName,
      partChineseName: [],
    };

    // 如果为新增剔除编译标记为否的配件名称

    for (let key in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[key]) {
        if(parseSign) {
          let isParseSign = this.listOfData.some(item =>  item.partChineseName === key && item.parseSign === 0);
          if(isParseSign) continue;
        }
        requestJson.partChineseName.push(key);
      }
    }
    return { ...requestJson, ...param };
  }


  checkAll(value: boolean): void {
    this.listOfData
      .filter(item => !(!item.partChineseName || !item.partNumber))
      .forEach(item => (this.mapOfCheckedId[item.partChineseName] = value));
    this.refreshStatus(value);
  }

  refreshStatus(value): void {
    this.isAllDisplayDataChecked = this.listOfData
      .filter(item => !!item.partChineseName)
      .every(item => this.mapOfCheckedId[item.partChineseName]);
    this.isIndeterminate =
      this.listOfData
        .filter(item => !!item.partChineseName)
        .some(item => this.mapOfCheckedId[item.partChineseName]) &&
      !this.isAllDisplayDataChecked;
    this.numberOfChecked = this.listOfData.filter(item => this.mapOfCheckedId[item.partChineseName]).length;
  }

  private listOfCache(): string[] {
    return Object.keys(this.mapOfCheckedId).filter(item => this.mapOfCheckedId[item]);
  }

}


